import * as THREE from 'three';
import {
    OrbitControls
} from 'three/addons/controls/OrbitControls.js';

export function init(container: HTMLElement) {
    const scene = new THREE.Scene();

    // 创建立方体
    const geometry = new THREE.BoxGeometry(100, 100, 100);
    const material = new THREE.MeshLambertMaterial(({
        color: new THREE.Color('orange')
    }));
    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(0, 0, 0);
    scene.add(mesh);

    // 创建点光源
    const pointLight = new THREE.PointLight(0xffffff, 10000);
    pointLight.position.set(80, 80, 80);
    scene.add(pointLight);

    // 创建坐标轴辅助器
    const axesHelper = new THREE.AxesHelper(200);
    scene.add(axesHelper);

    // 创建相机和渲染器
    const width = container.clientWidth;
    const height = container.clientHeight;

    const camera = new THREE.PerspectiveCamera(60, width / height, 1, 1000);
    camera.position.set(200, 200, 200);
    camera.lookAt(0, 0, 0);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(width, height);

    let animationId: number;

    function render() {
        renderer.render(scene, camera);
        animationId = requestAnimationFrame(render);
    }

    render();

    container.appendChild(renderer.domElement);

    const controls = new OrbitControls(camera, renderer.domElement);

    // 窗口大小变化处理
    function handleResize() {
        const width = container.clientWidth;
        const height = container.clientHeight;
        camera.aspect = width / height;
        camera.updateProjectionMatrix();
        renderer.setSize(width, height);
    }

    window.addEventListener('resize', handleResize);

    // 返回清理函数
    return function cleanup() {
        window.removeEventListener('resize', handleResize);
        if (animationId) {
            cancelAnimationFrame(animationId);
        }
        controls.dispose();
        renderer.dispose();
        if (container.contains(renderer.domElement)) {
            container.removeChild(renderer.domElement);
        }
    };
}
